import "./index.less";
import { View, Text } from "@tarojs/components";
import { useRef, useState, useEffect } from "react";

type IProps = {
  onConfirm?: () => void;
  onCancel?: () => void;
  onVisibleChange?: (visible: boolean) => void;
  children: React.ReactNode;
  trigger?: React.ReactNode;
  height?: string;
};

export default function MaskModal({
  onConfirm,
  onCancel,
  onVisibleChange,
  children,
  trigger,
  height = `${42 * 4 + 3 * 42}px`,
}: IProps) {
  const [visible, setVisible] = useState(false);
  const outRef = useRef(null);
  const innerRef = useRef(null);

  const handleClose = () => {
    setVisible(false);
  };

  useEffect(() => {
    onVisibleChange && onVisibleChange(visible);
  }, [visible]);

  const handleConfirm = () => {
    if (onConfirm) {
      onConfirm();
    }

    handleClose();
  };

  const handleCancel = () => {
    onCancel && onCancel();
    handleClose();
  };

  return (
    <View className="mask-modal">
      <View className="mask-trigger" onClick={() => setVisible(!visible)}>
        {trigger}
      </View>

      {visible && (
        <View className="mask" ref={outRef} onClick={handleCancel}>
          <View
            className="modal-container"
            ref={innerRef}
            style={visible ? { maxHeight: height } : {}}
            onClick={(e) => {
              e.stopPropagation();
            }}
          >
            <View className="action">
              <Text className="cancel" onClick={handleCancel}>
                取消
              </Text>
              <Text className="confirm" onClick={handleConfirm}>
                确定
              </Text>
            </View>
            {children}
          </View>
        </View>
      )}
    </View>
  );
}
